﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.EShop.Common.Utility;
using System.Data;
using Runda.EShop.Bll;
using Runda.EShop.Common.Entity;

namespace Runda.EShop.SaaS.SysManage
{
    public partial class UserAdd : BasePage
    {
        #region 属性

        public Guid UserID
        {
            get
            {
                if (ViewState["UserID"] == null)
                    return Guid.Empty;
                else
                    return new Guid(ViewState["UserID"].ToString());
            }
            set { ViewState["UserID"] = value; }
        }

        public bool IsAdd
        {
            get { return Convert.ToBoolean(ViewState["IsAdd"].ToString()); }
            set { ViewState["IsAdd"] = value; }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitForm();

                if (!string.IsNullOrEmpty(Request.QueryString["UserID"]))
                {
                    IsAdd = false;
                    UserID = new Guid(Request.QueryString["UserID"]);
                    SetFormData();
                }
                else
                {
                    IsAdd = true;
                    UserID = Guid.NewGuid();
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string Error = "";
            if (!TrySave(ref Error))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error", "alert('" + Error + "')", true);
                return;
            }
            ClientScript.RegisterStartupScript(this.GetType(), "SaveAndClose", "alert('保存成功.');parent.$.ligerDialog.hide();parent.$('#cphMain_cphMain_btnQuery').click();", true);
        }

        private void InitForm()
        {
            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = new SqlDbParameter();
            parm.ColumnName = "Deleted";
            parm.ColumnType = DbType.Byte;
            parm.ParameterName = "@Deleted";
            parm.ParameterValue = 0;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            SystemBll bll = new SystemBll();
            cblRoles.DataSource = bll.GetAll<SysRoleEntity>(parms);
            cblRoles.DataTextField = "RoleName";
            cblRoles.DataValueField = "RoleID";
            cblRoles.DataBind();             
        }

        private bool TrySave(ref string Message)
        {
            SystemBll bll = new SystemBll();
            SysUserEntity entity = null;

            //检查Account是否存在 
            List<SysUserEntity> entityList = new List<SysUserEntity>();
            if (IsAdd)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Account";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@Account";
                parm.ParameterValue = txtAccount.Text.Trim();
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);

                entityList = bll.GetAll<SysUserEntity>(parms);
                if (entityList.Count > 0)
                {
                    Message = "您输入的帐号已存在";
                    return false;
                }
            }
            else
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Account";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@Account";
                parm.ParameterValue = txtAccount.Text.Trim();
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);

                parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.NotEqual;
                parms.Add(parm);

                entityList = bll.GetAll<SysUserEntity>(parms);
                if (entityList.Count > 0)
                {
                    Message = "您输入的帐号已存在";
                    return false;
                }
            }

           //try save user info
            if (!IsAdd)
            {
                entity = bll.Get<SysUserEntity>(UserID);
            }
            else
            {
                entity = new SysUserEntity();
                //UserID = entity.UserID;
                entity.UserID = UserID;
                entity.Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(System.Configuration.ConfigurationManager.AppSettings["UserDefaultPassword"], "MD5");
                entity.CreatedBy = entity.LastModifyBy = base.User.Identity.LoginUser.UserID;
                entity.CreatedOn = entity.LastModifyOn = DateTime.Now;
            }

            entity.UserName = txtUserName.Text;
            entity.Account = txtAccount.Text.Trim();
            entity.Email = txtEmail.Text;
            entity.DeptName = txtDeptName.Text;            

            //保存权限     
            List<SysUserRoleRelationEntity> UserRoleList = new List<SysUserRoleRelationEntity>();
            SysUserRoleRelationEntity UserRoleEntity = null;
            foreach (ListItem item in cblRoles.Items)
            {
                if (item.Selected)
                {
                    UserRoleEntity = new SysUserRoleRelationEntity();
                    UserRoleEntity.RoleID = new Guid(item.Value);
                    UserRoleEntity.UserID = UserID;
                    UserRoleEntity.Deleted = false;
                    UserRoleList.Add(UserRoleEntity);
                }
            }

            entity.UserRoleRelationList = UserRoleList;

            bll.SaveUser(entity);

            if (!IsAdd)
            {
                DoOperationLog(EnumHelper.OperationType.Delete, "修改用户，ID:" + UserID);
            }
            else
            {
                DoOperationLog(EnumHelper.OperationType.Add, "增加用户，ID:" + UserID);
            }

            return true;

        }

        private void SetFormData()
        {
            if (UserID != Guid.Empty)
            {
                SysUserEntity entity = null;//
                SystemBll bll = new SystemBll();
                entity = bll.Get<SysUserEntity>(UserID);

                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "UserID";
                parm.ColumnType = DbType.Guid;
                parm.ParameterName = "@UserID";
                parm.ParameterValue = entity.UserID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                entity.UserRoleRelationList = bll.GetAll<SysUserRoleRelationEntity>(parms);

                txtAccount.Text = entity.Account;
                txtUserName.Text = entity.UserName;
                txtEmail.Text = entity.Email;
                txtDeptName.Text = entity.DeptName; 
                foreach (ListItem item in cblRoles.Items)
                {
                    Predicate<SysUserRoleRelationEntity> predicate =
                        delegate(SysUserRoleRelationEntity ent)
                        {
                            if (ent.RoleID == new Guid(item.Value)) return true;
                            return false;
                        };
                    bool IsExists = entity.UserRoleRelationList.Exists(predicate);
                    if (IsExists)
                        item.Selected = true;
                }

            }
        }
    }
}